<template>
  <div style="margin: 20px">
    <Form ref="formCustom" :model="formCustom" :rules="ruleCustom" :label-width="80">
      <FormItem label="原密码" prop="age" style="width: 300px">
        <Input type="text" v-model="formCustom.oldPsw" />
      </FormItem>
      <FormItem label="新密码" prop="passwd" style="width: 300px">
        <Input type="password" v-model="formCustom.newPsw" />
      </FormItem>
      <FormItem label="确认密码" prop="passwdCheck" style="width: 300px">
        <Input type="password" v-model="formCustom.passwdCheck" />
      </FormItem>
      <FormItem>
        <Button type="primary" @click="Submit('formCustom')">确定修改</Button>
      </FormItem>
    </Form>
  </div>
</template>

<script>
  export default {
    name: 'resetPassword',
    data () {
      const validatePass = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入新密码'))
        } else {
          if (this.formCustom.passwdCheck !== '') {
            // 对第二个密码框单独验证
            this.$refs.formCustom.validateField('passwdCheck')
          }
          callback()
        }
      }
      const validatePassCheck = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请再次输入密码'))
        } else if (value !== this.formCustom.newPsw) {
          callback(new Error('两次密码不一致!'))
        } else {
          callback()
        }
      }
      const validateAge = (rule, value, callback) => {
        if (!value) {
          return callback(new Error('请输入老密码'))
        }
      }

      return {
        formCustom: {
          newPsw: '',
          passwdCheck: '',
          oldPsw: ''
        },
        ruleCustom: {
          newPsw: [
            { validator: validatePass, trigger: 'blur' }
          ],
          passwdCheck: [
            { validator: validatePassCheck, trigger: 'blur' }
          ],
          oldPsw: [
            { validator: validateAge, trigger: 'blur' }
          ]
        }
      }
    },
    methods: {
      Submit (name) {
        this.$refs[name].validate((valid) => {
          if (valid) {
            this.submitPaw()
          }
        })
      },
      submitPaw() {
        this.$put('/api/user/psw', this.$qs.stringify({
          oldPsw: this.formCustom.oldPsw,
          newPsw: this.formCustom.newPsw
        })).then((res) => {
          if (res.code === 200) {
            this.$Message.success({
              duration: 3,
              content: '修改成功，3秒后跳转去重新登录',
              onClose: this.path()
            })
          }
        })
      },
      path() {
        // setTimeout(() => {
        //   this.formCustom = {}
        //   this.$router.push('/login')
        // }, 3100)
      }
    }
  }
</script>

<style scoped>

</style>
